/**
 * Created by liu on 16-3-4.
 */
$(function () {
    get_cart_goods();
    get_now_time();
    page_show_goods_info();
    add_to_price();
    page_show_free_goods_info();
    count_price();
});

function get_now_time() {
    var dateDigitToString = function (num) {
        return num < 10 ? '0' + num : num;
    };
    var currentDate = new Date(), year = dateDigitToString(currentDate.getFullYear()), month = dateDigitToString(currentDate.getMonth() + 1), date = dateDigitToString(currentDate.getDate()), hour = dateDigitToString(currentDate.getHours()), minute = dateDigitToString(currentDate.getMinutes()), second = dateDigitToString(currentDate.getSeconds());
    var formattedDateString = year + '年' + month + '月' + date + '日 ' + hour + ':' + minute + ':' + second;
    $('#time').text(formattedDateString);
}


function page_show_goods_info() {
    get_cart_goods().forEach(function (litm) {
        var good_info = "<tr class='h35'><td>" + litm.sort + "</td><td>" + litm.name + "</td><td>" + litm.price + "</td><td>" + litm.unit + "</td>" + "<td>" + litm.count + "</button>" + "</td><td id='" + litm.name + "time'>" + "<div class='div'>" + (litm.count - litm.free_count) * litm.price + "</div>元 </td></tr>";
        $('#no_button').append(good_info);
    });
}

function add_to_price() {
    get_cart_goods().forEach(function (goods) {
        if (free_goods_info()[goods.name])$('#' + goods.name + 'time').append('(原价:&nbsp;&nbsp' + goods.count * goods.price + '元)');
    })
}

function page_show_free_goods_info() {
    get_cart_goods().forEach(function (goods) {
        if (free_goods_info()[goods.name] && goods.count >= 3) {
            var cart = "<tr><td class='h35'>" + goods.sort + "</td><td>" + goods.name + "</td><td>" + goods.free_count + "</td></tr>";
            $('#get_goods').append(cart)
        }
    });
}
function count_price() {
    var total = 0;
    var save = 0;
    get_cart_goods().forEach(function (good) {
        total += good.count * good.price;
        save += good.free_count * good.price;
    });
    $('#total').append((total).toFixed(2));
    $('#save').append((save).toFixed(2));
}

function jump() {
    var item = {};
    get_cart_goods().forEach(function (value) {
        if (get_goods_inventory()[value.name]) {
            item[value.name] = get_goods_inventory()[value.name] - value.count;
            save_remain_count(item)
        }
    });
    return item;
}
function save_remain_count(good) {
    var url = '/payment/save_good_remain_count';
    var data = good;
    var success = function (data) {
    };
    var error = function () {
        alert('n')
    };
    ajax_post(url,data,success,error)
}

